package com.kelly.wager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends SherlockActivity implements OnClickListener {
	private static final int MAX_COUNT = 10;
	private static Toast toast = null;

	private EditText targetNameEdit;

	private LinearLayout mPersonInfoContainer;
	private ArrayList<LinearLayout> mPersonInfoItems = new ArrayList<LinearLayout>(0);
	private ArrayList<Person> mPersonList = new ArrayList<Person>(0);
	private EditText peopleCountEdit;

	private Button applyBtn;
	private Button resultBtn;

	private int mSelectedCount = 0;
	private int mCompleteBtnClickCount = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		targetNameEdit = (EditText)findViewById(R.id.target_name_edit);
		mPersonInfoContainer = (LinearLayout)findViewById(R.id.person_info_container);
		peopleCountEdit = (EditText)findViewById(R.id.how_many_people);
		applyBtn = (Button)findViewById(R.id.applyBtn);
		resultBtn = (Button)findViewById(R.id.resultBtn);
	}

	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(peopleCountEdit.getApplicationWindowToken(), 0);
	}

	public void onClickedResult(View view) {
		Collections.sort(mPersonList, new PersonComparator());

		String nameOrder = "";
		String targetName = targetNameEdit.getText().toString();
		if (StringUtils.isNotEmpty(targetName)) {
			nameOrder = targetName + " ";
		}

		nameOrder += getResources().getString(R.string.value_desc) + "\n\n";

		for (int i = 0; i < mPersonList.size(); i++) {
			nameOrder += (mPersonList.get(i).getIndex() + 1) + ". " + mPersonList.get(i).getName() + "\n";
		}

		for (int i = 0; i < mPersonList.size() - 1; i++) {
			for (int j = i + 1; j < mPersonList.size(); j++) {
				if (mPersonList.get(i).getValue() == mPersonList.get(j).getValue()) {
					nameOrder += mPersonList.get(i).getName() + "=" + mPersonList.get(j).getName() + "\n";
				}
			}
		}
		//NToast.showToast(toast, this, nameOrder, true);

		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(R.string.result);
		dialog.setMessage(nameOrder);
		dialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	public void onClickedApply(View view) {
		hideKeyboard();

		String personCount = getResources().getString(R.string.person_count);
		String message = String.format("1 <= %s <= %d.", personCount, MAX_COUNT);

		String number = peopleCountEdit.getText().toString();
		if (StringUtils.isEmpty(number)) {
			NToast.showToast(toast, this, message, true);
			return;
		}

		int count = Integer.parseInt(number);
		if (count < 2 || count > MAX_COUNT) {
			NToast.showToast(toast, this, message, true);
			return;
		}

		mSelectedCount = count;
		clearView();

		for (int i = 0; i < mSelectedCount; i++) {
			LinearLayout persionInfoItem = (LinearLayout)getLayoutInflater().inflate(R.layout.person_info_row, null);

			TextView personInfoIdTextView = (TextView)persionInfoItem.findViewById(R.id.person_info_id);
			String id = String.format("%2d.", i + 1);
			personInfoIdTextView.setText(id);

			Button saveBtn = (Button)persionInfoItem.findViewById(R.id.person_info_save_btn);
			saveBtn.setTag(Integer.valueOf(i));
			saveBtn.setOnClickListener(this);

			Button modifyBtn = (Button)persionInfoItem.findViewById(R.id.person_info_modify_btn);
			modifyBtn.setTag(Integer.valueOf(i));
			modifyBtn.setOnClickListener(this);

			Button completeBtn = (Button)persionInfoItem.findViewById(R.id.person_info_complete_btn);
			completeBtn.setTag(Integer.valueOf(i));
			completeBtn.setOnClickListener(this);

			mPersonInfoContainer.addView(persionInfoItem);
			mPersonInfoItems.add(persionInfoItem);
		}

	}

	private void clearView() {
		if (applyBtn.getText().equals(getResources().getString(R.string.apply))) {
			applyBtn.setText(R.string.reset);
		} else {
			applyBtn.setText(R.string.apply);
		}

		removeAllItems();
		resultBtn.setVisibility(View.GONE);
		mCompleteBtnClickCount = 0;
		mPersonList.clear();
	}

	public void removeAllItems() {
		Iterator<LinearLayout> it = mPersonInfoItems.iterator();
		while (it.hasNext()) {
			LinearLayout persionInfoItem = it.next();
			LinearLayout parent = (LinearLayout)persionInfoItem.getParent();
			parent.removeView(persionInfoItem);
			it.remove();
		}
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.person_info_save_btn) {
			int index = (Integer)view.getTag();
			LinearLayout persionInfoItem = (LinearLayout)view.getParent().getParent();
			EditText nameText = (EditText)persionInfoItem.findViewById(R.id.person_info_name);
			TextView valueTextLabel = (TextView)persionInfoItem.findViewById(R.id.person_info_value_label);
			EditText valueText = (EditText)persionInfoItem.findViewById(R.id.person_info_value);
			if (StringUtils.isEmptyOrWhitespace(nameText.getText().toString()) || StringUtils.isEmptyOrWhitespace(valueText.getText().toString())) {
				return;
			}

			boolean find = false;
			for (Person person : mPersonList) {
				if (person.getIndex() == index) {
					find = true;
					person = new Person(index, nameText.getText().toString(), Integer.parseInt(valueText.getText().toString()));
				}
			}

			if (!find) {
				mPersonList.add(new Person(index, nameText.getText().toString(), Integer.parseInt(valueText.getText().toString())));
			}

			nameText.setEnabled(false);
			valueTextLabel.setVisibility(View.GONE);
			valueText.setVisibility(View.GONE);
			view.setVisibility(View.GONE);

			Button modifyBtn = (Button)persionInfoItem.findViewById(R.id.person_info_modify_btn);
			modifyBtn.setVisibility(View.VISIBLE);

			Button completeBtn = (Button)persionInfoItem.findViewById(R.id.person_info_complete_btn);
			completeBtn.setVisibility(View.VISIBLE);
		} else if (view.getId() == R.id.person_info_modify_btn) {
			LinearLayout persionInfoItem = (LinearLayout)view.getParent().getParent();

			TextView valueTextLabel = (TextView)persionInfoItem.findViewById(R.id.person_info_value_label);
			EditText valueText = (EditText)persionInfoItem.findViewById(R.id.person_info_value);
			valueTextLabel.setVisibility(View.VISIBLE);
			valueText.setVisibility(View.VISIBLE);

			view.setVisibility(View.GONE);

			Button completeBtn = (Button)persionInfoItem.findViewById(R.id.person_info_complete_btn);
			completeBtn.setVisibility(View.GONE);

			Button saveBtn = (Button)persionInfoItem.findViewById(R.id.person_info_save_btn);
			saveBtn.setVisibility(View.VISIBLE);

			resultBtn.setVisibility(View.GONE);
		} else if (view.getId() == R.id.person_info_complete_btn) {
			view.setEnabled(false);
			LinearLayout persionInfoItem = (LinearLayout)view.getParent().getParent();
			Button modifyBtn = (Button)persionInfoItem.findViewById(R.id.person_info_modify_btn);
			modifyBtn.setVisibility(View.GONE);

			mCompleteBtnClickCount++;

			if (mSelectedCount == mPersonList.size() && mSelectedCount == mCompleteBtnClickCount) {
				resultBtn.setVisibility(View.VISIBLE);
			}
		}
	}
}
